package cn.stylefeng.guns.modular.system.service.impl;


import cn.stylefeng.guns.modular.system.dto.DeviceTotalQuery;
import cn.stylefeng.guns.modular.system.model.DeviceTotal;
import cn.stylefeng.guns.modular.system.repository.DeviceTotalRepository;
import cn.stylefeng.guns.modular.system.service.IDeviceTotalService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Service;


import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

@Service
public class DeviceTotalServiceImpl implements IDeviceTotalService {
    @Autowired
    private DeviceTotalRepository deviceTotalRepository;

    @Override
    public Optional<DeviceTotal> selectById(String deviceTotalId) {
        return deviceTotalRepository.findById(deviceTotalId);

    }

    @Override
    public Object selectList(DeviceTotalQuery o) {
        List<DeviceTotal> deviceTotalList = new ArrayList<>();
        if (StringUtils.isNoneBlank(o.getDeviceid()) && StringUtils.isNoneBlank(o.getAction())) {
            deviceTotalList = deviceTotalRepository.findAllByDeviceidAndAction(o.getDeviceid(), o.getAction());
        } else if (StringUtils.isBlank(o.getDeviceid()) && StringUtils.isNotBlank(o.getAction())) {
            deviceTotalList = deviceTotalRepository.findAllByAction(o.getAction());
        } else if (StringUtils.isNoneBlank(o.getDeviceid())) {
            deviceTotalList = deviceTotalRepository.findAllByDeviceid(o.getDeviceid());
        } else if (o.getStartDate() != null && o.getStartDate().equals(o.getEndDate())) {
            deviceTotalList = deviceTotalRepository.findAllByDate(o.getStartDate());
        } else {
            deviceTotalList = deviceTotalRepository.findAll();
        }

        if (o.getStartDate() == null) {
            o.setStartDate((long) 0);
        }
        if (o.getEndDate() == null) {
            o.setEndDate(Long.MAX_VALUE);
        }

        deviceTotalList = deviceTotalList.stream().filter(deviceTotal -> deviceTotal.getDate() >= o.getStartDate() && deviceTotal.getDate() <= o.getEndDate()).sorted(Comparator.comparing(DeviceTotal::getDate)).collect(Collectors.toList());
        return deviceTotalList;
    }

    @Override
    public void insert(DeviceTotal deviceTotal) {
        deviceTotalRepository.insert(deviceTotal);

    }

    @Override
    public void deleteById(String deviceTotalId) {
        deviceTotalRepository.deleteById(deviceTotalId);
    }

    @Override
    public void updateById(DeviceTotal deviceTotal) {
        deviceTotalRepository.save(deviceTotal);
    }
}
